#include "image.h"

Image::Image(QWidget *_parent, QImage *_img) : QWidget(_parent), image(_img){
    zoom = 100.0;

    QSplitter *horizontalSplitter = new QSplitter(this);
    horizontalSplitter->setOrientation(Qt::Vertical);

	QLabel* zoomLabel = new QLabel(tr("Zoom:"));
	zoomDoubleSpinBox = new QDoubleSpinBox();
    zoomDoubleSpinBox->setSuffix("%");
    zoomDoubleSpinBox->setRange(0.01, 100000.0);
    zoomDoubleSpinBox->setSingleStep(25.0);
    zoomDoubleSpinBox->setValue(zoom);
    connect(zoomDoubleSpinBox, SIGNAL(valueChanged(double)), this, SLOT(changeZoom(double)));

    QHBoxLayout *zoomLayout = new QHBoxLayout;
    zoomLayout->addWidget(zoomLabel);
    zoomLayout->addWidget(zoomDoubleSpinBox);
	zoomLayout->addStretch();

    graphicView = new QGraphicsView(horizontalSplitter);
    graphicView->setDragMode(QGraphicsView::ScrollHandDrag);
    graphicView->setAlignment(Qt::AlignCenter);
    graphicView->setResizeAnchor(QGraphicsView::AnchorUnderMouse);

    QWidget *zoomWidget = new QWidget(horizontalSplitter);
    zoomWidget->setLayout(zoomLayout);
    zoomWidget->setMaximumHeight(70);

    horizontalSplitter->addWidget(graphicView);
    horizontalSplitter->addWidget(zoomWidget);


    resize(600, 500);

    QVBoxLayout *mainLayout = new QVBoxLayout;
    mainLayout->addWidget(horizontalSplitter);
//    mainLayout->addWidget(graphicView);
//    mainLayout->addLayout(zoomLayout);

    setLayout(mainLayout);
}

Image::~Image(){
    if (image) delete image;
}

void Image::normalSize(){
    zoom = 100.0;
    zoomDoubleSpinBox->setValue(zoom);
}

void Image::zoomIn(){
    zoom += 25.0;
    zoomDoubleSpinBox->setValue(zoom);
}

void Image::zoomOut(){
    zoom -= 25.0;
    zoomDoubleSpinBox->setValue(zoom);
}

void Image::fitToWindow(){
    double imageAspectRatio = (double)image->width()/(double)image->height();
    double areaAspectRatio = (double)graphicView->width()/(double)graphicView->height();

    if (areaAspectRatio < imageAspectRatio){
        zoom = (double)graphicView->width()/(double)image->width();
    }else{
        zoom = (double)graphicView->height()/(double)image->height();
    }

    zoom -= 0.003;//error
    zoom *= 100;
    zoomDoubleSpinBox->setValue(zoom);
}

void Image::setAreaSize(int _w, int _h){
    graphicView->setFixedSize(_w, _h);
}

QImage *Image::getImage(){
    return image;
}

void Image::setImage(QImage *_img){
    delete image;
    image = _img;
}

void Image::update(QImage *_img){
    if (_img){
        delete image;
        image = _img;
    }

    int w = image->width()*zoom/100.0, h = image->height()*zoom/100.0;
    QImage printImage = image->scaled(w, h, Qt::KeepAspectRatio);

    delete graphicView->scene();

    QGraphicsScene *scene = new QGraphicsScene;
    scene->addPixmap(QPixmap::fromImage(printImage));
    graphicView->setScene(scene);
}

void Image::changeZoom(double _z){
    zoom = _z;
    update();
}
